
package com.xifan.news.util;

import com.xifan.news.data.NewsInfo;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class WebUtil {

    public static final String GUNDONG_NEWS_URL = "http://www.cqwu.edu.cn/gdxw/index.htm";

    public static List<NewsInfo> getNewsList() {
        List<NewsInfo> list = new ArrayList<NewsInfo>();
        try {
            NewsInfo info;

            URL url = new URL(GUNDONG_NEWS_URL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-type", "gb2312");
            connection.setRequestProperty("Content-type", "text/html");
            connection.setInstanceFollowRedirects(true);
            connection.connect();
            Document doc = Jsoup.parse(connection.getInputStream(), "gb2312", GUNDONG_NEWS_URL);
            Elements elements = doc.select("div.f-left").select("a");
            if (elements.size() > 0) {
                for (Element element : elements) {
                    info = new NewsInfo();
                    info.setTitle(element.attr("title"));
                    info.setUrl(element.attr("href"));
                    list.add(info);
                }
                Elements dateElements = doc.select("div.f-right");
                int count = 0;
                for (Element dateElement : dateElements) {
                    list.get(count).setDate(dateElement.html().trim());
                    count++;
                }
            }
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return list;
    }

}
